package com.org.utils.conf;

import java.util.*;

/**
 * 宏配置管理类
 * 
 * @author 
 */
public class ConfigureMacro {
	private static Map<String, String> configureMacros = new Hashtable<String, String>();

	/**
	 * 构建器
	 * 
	 */
	public ConfigureMacro() {

	}

	/**
	 * 新增一个宏定义
	 * 
	 * @param name
	 * @param value
	 */
	public static synchronized void addMacro(String name, String value) {
		configureMacros.put(name, value);
		BaseConfigure.clearCache(); // 刷新配置文件缓存
	}

	/**
	 * 去除一个宏定义
	 * 
	 * @param name
	 */
	public static synchronized void removeMacro(String name) {
		configureMacros.remove(name);
		BaseConfigure.clearCache(); // 刷新配置文件缓存
	}

	/**
	 * 获取默认配置文件中的宏定义
	 * 
	 * @param name
	 * @return String
	 */
	public static synchronized String getMacro(String name) {
		String result = null;
		result = configureMacros.get(name);
		return result;
	}

	/**
	 * 获取配置属性的真实路径
	 * 
	 * @param value
	 * @return String
	 */
	public static synchronized String getRealValue(String value) {
		if (value == null)
			return null;
		Set<String> keys = configureMacros.keySet();
		Iterator<String> keyIterator = keys.iterator();
		while (keyIterator.hasNext()) {
			String key = (String) keyIterator.next();
			int index = value.indexOf("${" + key + "}");
			if (index != -1)
				value = replace(value, "${" + key + "}",
						(String) configureMacros.get(key));
		}
		return value;
	}

	/**
	 * 字符串替换方法 (私有)
	 * 
	 * @param line
	 * @param oldString
	 * @param newString
	 * @return String
	 */
	private static String replace(String line, String oldString,
			String newString) {
		if (line == null)
			return null;
		int i = 0;
		if ((i = line.indexOf(oldString, i)) >= 0) {
			char line2[] = line.toCharArray();
			char newString2[] = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j;
			for (j = i; (i = line.indexOf(oldString, i)) > 0; j = i) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
			}

			buf.append(line2, j, line2.length - j);
			return buf.toString();
		} else {
			return line;
		}
	}

}
